package com.mcxx.modules.extremepoverty.service.impl;

import cn.hutool.core.util.IdUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.extremepoverty.service.ExOrganizationService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.family.dao.read.FamilyMemberHistoryReadDao;
import com.mcxx.modules.miniSalvation.family.dto.OrgSupperCheckDTO;
import com.mcxx.modules.miniSalvation.family.dto.OrganizationDTO;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberHistoryEntity;
import com.mcxx.modules.miniSalvation.family.entity.OrganizationEntity;
import com.mcxx.modules.miniSalvation.family.param.OrganizationParam;
import com.mcxx.modules.miniSalvation.family.service.read.OrganizationReadService;
import com.mcxx.modules.miniSalvation.family.service.write.OrganizationWriteService;
import com.mcxx.modules.miniSalvation.order.dto.OrderCareLinkDTO;
import com.mcxx.modules.miniSalvation.order.param.CareLinkParam;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("exOrganizationService")
@TaTransactional
public class ExOrganizationServiceImpl extends BaseService implements ExOrganizationService {

    @Autowired
    private OrganizationReadService organizationReadService;
    @Autowired
    private OrganizationWriteService organizationWriteService;
    @Autowired
    private FamilyMemberHistoryReadDao familyMemberHistoryReadDao;
    @Autowired
    private ExportExcelService exportExcelService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;


    @Override
    public int addOrgName(OrganizationDTO dto, UserAccountVo userAccountVo) {
        int i = organizationReadService.checkName(dto.getName());
        OrganizationEntity oEntity = new OrganizationEntity();
        BeanUtils.copyProperties(dto,oEntity);
//        oEntity.setAreaCode(dto.getAreaCode());
//        oEntity.setName(dto.getName());
        if(StringUtils.isEmpty(dto.getId())){
            if(i <= 0){
                oEntity.setStatus(Constant.OrganizationState.DISABLED);
                oEntity.setOrgType(Constant.OrganizationType.SUPPORT);
                oEntity.setCreateTime(new Date());
                oEntity.setOperator(userAccountVo.getUserId());
                oEntity.setParentId("0");
                oEntity.setId(IdUtil.simpleUUID());
                int rst = organizationWriteService.insertIgnoreNull(oEntity);
                if(rst <= 0){
                    log.info("name = {},说明保存供养机构信息失败", dto.getName());
                    throw new BizException("-1", "保存供养机构信息失败");
                }
            }else{
                log.info("{}-该名称机构已存在", dto.getName());
                throw new BizException("-1", "该名称机构已存在");
            }
        }else{

            oEntity.setId(dto.getId());
            int rst = organizationWriteService.updateIgnoreNull(oEntity);
            if(rst <= 0){
                log.info("name = {},说明保存供养机构信息失败", dto.getName());
                throw new BizException("-1", "保存供养机构信息失败");
            }
        }

        return 1;
    }


    @Override
    public int updateOrgById(OrganizationDTO dto, UserAccountVo userAccountVo) {
        OrganizationEntity oEntity = new OrganizationEntity();
        BeanUtils.copyProperties(dto, oEntity);
        oEntity.setOperator(userAccountVo.getUserId());
        oEntity.setCreateTime(DateUtil.getDate());
        int rst = organizationWriteService.updateIgnoreNull(oEntity);
        if(rst <= 0){
            log.info("id = {},说明保存供养机构信息失败", oEntity.getId());
            throw new BizException("-1", "保存供养机构信息失败");
        }
        return 1;
    }

    @Override
    public Page queryByOrderAndOrgId(OrgSupperCheckDTO dto, PageParam pageParam){
        familyMemberHistoryReadDao.beginPager(pageParam);
        FamilyMemberHistoryEntity entity = new FamilyMemberHistoryEntity();
        entity.setId(dto.getId());
        entity.setIdcard(dto.getIdCard());
        entity.setName(dto.getName());
        entity.setSendMonth(DateUtil.getMonthString());
        List<FamilyMemberHistoryEntity> list = familyMemberHistoryReadDao.queryByOrderAndOrgId(entity);

        return familyMemberHistoryReadDao.endPager(list);
    }


    @Override
    public BaseResult<String> updateOrgStateById(OrgSupperCheckDTO dto){
        BaseResult<String> result = new BaseResult<String>();
        result.setCode("0");
        result.setMsg("操作成功");
        Integer operation = dto.getOperation();
        Map<String,Object> params = new HashMap<String,Object>();
        StringBuffer resuData = new StringBuffer();
        StringBuffer updateIds = new StringBuffer();

        List<OrganizationEntity> list = organizationReadService.queryOrgByIds(dto.getIds().split(","));
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException(FailureCode.ERR_10003);
        }

        for(OrganizationEntity entity : list){

            if(operation == entity.getStatus()){
                resuData.append(entity.getName());
            }else{

                updateIds.append(entity.getId()).append(",");
            }
        }
        String ids = updateIds.toString();

        if(StringUtils.isNotBlank(ids)){
            ids = ids.substring(0,ids.length()-1);
            params.put("status",operation);
            params.put("ids",ids.split(","));
            int res = organizationWriteService.updateStatus(params);
            if(res <= 0){
                result.setCode("-1");
                result.setMsg("操作异常，修改失败");
            }
        }

        if(resuData.length() > 0){
            result.setMsg("选中记录中包含已操作的记录");
            result.setData(resuData.toString());
        }
        return result;
    }


    @Override
    public int modifyStatus(String id,String status){
        int res = organizationWriteService.modifyStatus(id,status);
        if(res <= 0){
            throw new BizException("-1","操作异常,请联系管理员");
        }
        return res;
    }


    @Override
    public ExcelInfo exportOrganizationList(OrganizationParam param, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param, accountVo);
        param.setSendMonth(DateUtil.getMonthString());

        List<OrganizationDTO> list = organizationReadService.exportOrganizationList(param);


        ExcelInfo excelInfo = exportExcelService.exportOrgOpLogs(OrganizationDTO.class,list,"供养机构信息.xls",
                "供养机构信息","供养机构信息",false,null);



        return excelInfo;
    }



}
